#include "game.h"
void menu()
{
	printf("****************欢迎来到三子棋游戏系统****************\n");
	printf("****************1.开始游戏****************\n");
	printf("****************0.退出游戏****************\n");
}
void initBoard(char board[ROW][COL],int row, int col)					//初始化棋盘
{
	for (int i = 0; i < row; i++)
	{
		for (int j = 0; j < col; j++)
		{
			board[i][j] = ' ';
		}
	}
}
void printBoard(char board[ROW][COL], int row, int col)					//打印棋盘
{
	for (int i = 0; i < row; i++)
	{
		for (int j = 0; j < col; j++)
		{
			printf(" %c ", board[i][j]);
			if (j < col - 1)
			{
				printf("|");
			}
		}
		printf("\n");
		for (int j = 0; j < col; j++)
		{
			if (i < row - 1)
			{
				printf("---");
				if (j < col - 1)
				{
					printf("|");
				}
			}
		}
		printf("\n");
	}
}
void play_Move(char board[ROW][COL], int row, int col)						//人下棋
{
	int i=1, j = 0;
	while (1)
	{
		printf("输入位置>");
		scanf("%d %d", &i, &j);
		printf("\n");
		if (i > 0 && i < row + 1 && j>0 && j < col + 1)
		{
			if (board[i - 1][j - 1] == ' ')
			{
				board[i - 1][j - 1] = '*';
				break;
			}
			else
			{
				printf("该处已落子，请重新下棋\n");
			}
		}
		else
		{
			printf("位置有误请重新输入\n");
		}
	}
}
void robat_Move(char board[ROW][COL], int row, int col)					//电脑下棋
{
	printf("电脑下棋>\n");
	while (1)
	{
		int i = rand() % 3;
		int j = rand() % 3;
		if (board[i][j] == ' ')
		{
			board[i][j] = '#';
			break;
		}
	}
}

//判断棋盘是否填满
int IsFull(char board[ROW][COL], int row, int col)
{
	for (int i = 0; i < row; i++)
	{
		for (int j = 0; j < col; j++)
		{
			if (board[i][j] == ' ')
				return 0;
		}
	}
	return 1;
}
//判断输赢
char IsWIn(char board[ROW][COL], int row, int col)
{
	//判断横线
	for (int i = 0; i < row; i++)
	{
		if (board[i][0] == board[i][1] && board[i][1] == board[i][2] && board[i][0] != ' ')
		{
			return board[i][0];
		}
	}
	//判断竖线
	for (int j = 0; j < col; j++)
	{
		if (board[0][j] == board[1][j] && board[1][j] == board[2][j] && board[0][j] != ' ')
		{
			return board[0][j];
		}
	}
	//判断对角线
	if (board[2][0] == board[1][1] && board[1][1] == board[0][2] && board[1][1] != ' ')
		return board[1][1];
	if (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[1][1] != ' ')
		return board[1][1];
	if (IsFull(board, ROW, COL) == 1)
		return 'Q';
}
void game()
{
	char board[ROW][COL] = { 0 };
	char ret = 0;
	initBoard(board, ROW, COL);						//初始化棋盘
	printBoard(board, ROW, COL);						//打印棋盘
	while (1)
	{
		//人下棋
		play_Move(board, ROW, COL);
		printBoard(board, ROW, COL);
		ret = IsWIn(board, ROW, COL);
		if (ret == '*')
		{
			printf("人类获胜\n");
			break;
		}
		if (ret == 'Q')
		{
			printf("平局\n");
			break;
		}
		//电脑下棋
		robat_Move(board, ROW, COL);
		printBoard(board, ROW, COL);
		ret = IsWIn(board, ROW, COL);
		if (ret == '#')
		{
			printf("电脑获胜\n");
			break;
		}
	}
}
